package com.prothink.threadadmindemo.controller;

/**
 * Java多线程：写一下两个线程交替打印 0~100 的奇偶数
 */
public class JiaXiaoCaoController {
    static class Jishu implements Runnable{
        private int max;
        private int current = 2;
        public Jishu(int max){
            this.max = max;
        }

        @Override
        public void run() {
            while (current <= max){
                synchronized (this){
                    while (current > max || current % 2 != 0){
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    System.out.println(Thread.currentThread().getName()+":"+current);
                    current += 2;
                    notifyAll();
                }
            }
        }
    }

    static class Oushu implements Runnable{
        private int max;
        private int current = 1;
        public Oushu(int max){
            this.max = max;
        }

        @Override
        public void run() {
            while (current <= max){
                synchronized (this){
                    while (current > max || current %2 == 0){
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    System.out.println(Thread.currentThread().getName()+":"+current);
                    current += 2;
                    notifyAll();
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread jishu = new Thread(new Jishu(100),"Jishu");
        Thread oushu = new Thread(new Oushu(100),"oushu");
        jishu.start();
        oushu.start();
    }

}
